<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.url" clearable placeholder="请求地址（模糊匹配）" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.methodName" clearable placeholder="方法名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.bodyParams" clearable placeholder="请求参数（模糊匹配）" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.errorMsg" clearable placeholder="错误消息（模糊匹配）" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.requestResult" clearable placeholder="请求结果（模糊匹配）" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />

        <el-select v-model="query.isSuccess" clearable filterable
                   placeholder="是否成功" style="width: 120px;" class="filter-item" @change="crud.toQuery" >
          <el-option
            v-for="item in dict.is_success"
            :key="item.id"
            :label="item.label"
            :value="item.value" />
        </el-select>

        <el-date-picker
          class="filter-item"
          v-model="query.createTime"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>

        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" >
        <el-button
          :loading="reuploadAllLoading"
          slot="right"
          v-permission="permission.edit"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-refresh"
          @click="reuploadAll()"
        >
          一键重传
        </el-button>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="1000px">
        <el-form :inline="true" ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="请求地址">
            <el-input v-model="form.url" style="width: 830px;" />
          </el-form-item>

          <el-form-item label="请求方法">
            <el-input v-model="form.methodName" style="width: 140px;" />
          </el-form-item>

          <el-form-item label="是否成功">
            <el-select  v-model="form.isSuccess" filterable placeholder="请选择" style="width: 140px;" >
              <el-option
                v-for="item in dict.is_success"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="重式次数">
            <el-input v-model="form.retriesNum" style="width: 128px;" />
          </el-form-item>


          <el-form-item label="请求体参数">
            <el-input v-model="form.bodyParams" :rows="4" type="textarea" style="width: 830px;" />
          </el-form-item>

          <el-form-item label="请求头参数">
            <el-input v-model="form.headerParams" :rows="4" type="textarea" style="width: 830px;" />
          </el-form-item>

          <el-form-item label="返回结果">
            <el-input v-model="form.requestResult" :rows="4" type="textarea" style="width: 830px;" />
          </el-form-item>

          <el-form-item label="错误消息">
            <el-input v-model="form.errorMsg" :rows="4" type="textarea" style="width: 830px;" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="url" label="请求地址"  width="450px;" >
          <div slot-scope="scope">
            <a :href="scope.row.url" style="color: #1482f0">{{scope.row.url}}</a>
          </div>
        </el-table-column>
        <el-table-column prop="methodName" label="方法名称" width="200px;"/>
        <el-table-column prop="isSuccess" label="是否成功" width="100px;" align="center">
          <el-tag slot-scope="scope" :type="getTagType(scope.row.isSuccess)" >
            {{ dict.label.is_success[scope.row.isSuccess] }}
          </el-tag>
        </el-table-column>

        <el-table-column prop="summarize" label="概述" width="300px;" align="center"/>

        <el-table-column prop="retriesNum" label="重式次数" width="100px;" align="center"/>

        <el-table-column prop="elapsedTime" label="请求耗时" width="100px;" align="center"/>
        <el-table-column prop="createTime" label="请求时间" width="180px;" align="center"/>
        <el-table-column prop="createBy" label="请求人" width="100px;" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="180px;" align="center"/>
        <el-table-column prop="updateBy" label="更新人" width="100px;" align="center"/>

<!--        <el-table-column prop="params" label="请求参数" />

        <el-table-column prop="errorMsg" label="错误消息" />

        <el-table-column prop="requestResult" label="请求结果" />-->

        <el-table-column v-if="checkPer(['admin','sysExternalWebserviceLog:edit','sysExternalWebserviceLog:del'])" fixed="right" label="操作" width="250px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission" >
              <template slot="view">
                <el-button  size="mini" icon="el-icon-search" @click="viewDetails(scope.row)"></el-button>
                <el-popconfirm
                  title="确认重传吗？"
                  @confirm="reuploadOne(scope.row)"
                >
                  <el-button slot="reference"  size="mini" type="warning" icon="el-icon-refresh" :disabled="scope.row.isSuccess == '1'"></el-button>
                </el-popconfirm>

              </template>
            </udOperation>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />

      <!--  抽屉查看    -->
      <el-drawer
        title="日志详情"
        :visible.sync="drawer"
        :direction="direction"
        size="50%">
        <div class="app-container">
          <el-descriptions :column="1" size="medium">
            <el-descriptions-item label="请求地址">{{detailsData.url}}</el-descriptions-item>
            <el-descriptions-item label="请求方法">{{detailsData.methodName}}</el-descriptions-item>
            <el-descriptions-item label="是否成功">
              <el-tag :type="getTagType(detailsData.isSuccess)" >
                {{ dict.label.is_success[detailsData.isSuccess] }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="请求体参数">
              <div @mouseover="paramsButt = true" @mouseleave="paramsButt = false" style="width: 100%;height: 100%;">
                <el-card v-show="paramsView" shadow="never"  style="width: 100%;position: relative">
                  <pre>{{paramsView}}</pre>
                  <div v-show="paramsButt" style="position: absolute; bottom: 0;right: 0;background-color: #d3dce6">
                    <a @click="paramsView = formatJson(detailsData.bodyParams)" style="margin: 5px 2px;color: white">
                      格式化
                    </a>
                  </div>
                </el-card>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="请求头参数">
              <div @mouseover="paramsButt1 = true" @mouseleave="paramsButt1 = false" style="width: 100%;height: 100%;">
                <el-card v-show="paramsView1" shadow="never"  style="width: 100%;position: relative">
                  <pre>{{paramsView1}}</pre>
                  <div v-show="paramsButt1" style="position: absolute; bottom: 0;right: 0;background-color: #d3dce6">
                    <a @click="paramsView1 = formatJson(detailsData.headerParams)" style="margin: 5px 2px;color: white">
                      格式化
                    </a>
                  </div>
                </el-card>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="请求结果">
              <div @mouseover="requestResultButt = true" @mouseleave="requestResultButt = false" style="width: 100%;height: 100%;">
                <el-card v-show="requestResultView" shadow="never" style="width: 100%; position: relative">
                  <pre>{{requestResultView}}</pre>
                  <div v-show="requestResultButt" style="position: absolute; bottom: 0;right: 0;background-color: #d3dce6">
                    <a @click="requestResultView = formatJson(detailsData.requestResult)" style="margin: 5px 2px;color: white">
                      格式化
                    </a>
                  </div>
                </el-card>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="错误概述">{{detailsData.summarize}}</el-descriptions-item>
            <el-descriptions-item label="错误消息">
              <el-card v-show="detailsData.errorMsg" shadow="never" style="width: 100%; position: relative">
                <pre>{{detailsData.errorMsg}}</pre>
              </el-card>
            </el-descriptions-item>
            <el-descriptions-item label="请求耗时">{{detailsData.elapsedTime}}</el-descriptions-item>
            <el-descriptions-item label="重式次数">{{detailsData.retriesNum}}</el-descriptions-item>
            <el-descriptions-item label="请求时间">{{detailsData.createTime}}</el-descriptions-item>
            <el-descriptions-item label="请求人">{{detailsData.createBy}}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{detailsData.updateTime}}</el-descriptions-item>
            <el-descriptions-item label="更新人">{{detailsData.updateBy}}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import crudsysExternalWebserviceLog from '@/api/system/sysExternalWebserviceLog'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, url: null, methodName: null, bodyParams: null, headerParams: null, summarize: null, errorMsg: null, isSuccess: null, retriesNum: null, requestResult: null, elapsedTime: null, createTime: null, createBy: null, updateTime: null, updateBy: null }
export default {
  name: 'sysExternalWebserviceLog',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['is_success'],
  cruds() {
    return CRUD({
      title: 'Webservice请求日志',
      url: 'api/sysExternalWebserviceLog',
      idField: 'id',
      sort: 'id,desc',
      optShow: {
        add: false,
        edit: true,
        del: true,
        download: false,
        reset: true,
        import: false
      },
      crudMethod: { ...crudsysExternalWebserviceLog }})
  },
  data() {
    return {
      drawer: false,
      direction: 'rtl',
      detailsData: {},
      paramsView: '',//JSON格式内容
      paramsView1: '',//JSON格式内容
      requestResultView: '',//JSON格式内容
      paramsButt: false, //显示格式按钮
      paramsButt1: false, //显示格式按钮
      requestResultButt: false,//显示格式按钮
      reuploadAllLoading: false,//加载
      permission: {
        add: ['admin', 'sysExternalWebserviceLog:add'],
        edit: ['admin', 'sysExternalWebserviceLog:edit'],
        del: ['admin', 'sysExternalWebserviceLog:del']
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'url', display_name: '请求地址' },
        { key: 'methodName', display_name: '方法名称' },
        { key: 'bodyParams', display_name: '请求体参数' },
        { key: 'headerParams', display_name: '请求头参数' },
        { key: 'requestMethod', display_name: '请求方式' },
        { key: 'errorMsg', display_name: '错误消息' },
        { key: 'isSuccess', display_name: '是否成功' },
        { key: 'requestResult', display_name: '请求结果' }
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    //查看详情
    viewDetails(row){
      this.detailsData = row;
      this.paramsView = row.bodyParams;
      this.paramsView1 = row.headerParams;
      this.requestResultView = row.requestResult;
      this.drawer=true;
    },
    getTagType(result){
      if(result == '1' ){
        return 'success';
      }else if(result == '0'){
        return 'danger';
      }else{
        return '';
      }
    },
    formatJson(jsonObj) {
      // 是json，格式化输出
      if(jsonObj){
        return JSON.parse(jsonObj)
      }
      return jsonObj;
    },
    //重新上传
    reuploadOne(row){
      crudsysExternalWebserviceLog.reuploadOne(row).then(res =>{
        this.$notify({
          title: '成功',
          message: '重传成功！',
          type: 'success'
        });
        this.crud.refresh();
      }).catch(err => {
        this.reuploadAllLoading = false;
        this.crud.refresh();
      })
    },
    //一键上传
    reuploadAll(){
      this.$confirm(`确认一键重传所有失败的日志吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.reuploadAllLoading = true;
        crudsysExternalWebserviceLog.reuploadAll().then(res =>{
          this.reuploadAllLoading = false;
          this.$notify({
            title: '成功',
            message: '重传成功！',
            type: 'success'
          });
          this.crud.refresh();
        }).catch(err => {
          this.reuploadAllLoading = false;
          this.crud.refresh();
        })
      }).catch(() => {
      })

    }
  }
}
</script>

<style scoped>
  pre {
    white-space: pre-wrap;
    word-wrap: break-word;
  }
</style>
